/*
 * Filename:  UsmcDbDao.java
 * Copyright:  Raisecom Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * Description:  <description>
 * Author:  donghu
 * Edit-time:  2016-5-4
 * Modify content:  <modify content>
 */
package com.gutetec.cms.usmc.db.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.dropwizard.hibernate.AbstractDAO;

/**
 * 
 * <parent of usmc model db dao>
 * <Function details>
 * @author  donghu
 * @version  [Version, 2016-5-4]
 * @see  [Classs/Method]
 * @since  [Product/Model Version]
 */
public class UsmcDbDao<E> extends AbstractDAO<E>
{
    
    private static final Logger logger = LoggerFactory.getLogger(UsmcDbDao.class);
    
    private SessionFactory sessionFactory;
    
    protected Session session;
    
    /**
     * <>
     */
    public UsmcDbDao(SessionFactory sessionFactory)
    {
        super(sessionFactory);
        this.sessionFactory = sessionFactory;
    }
    
    protected Session currentSession()
    {
        return this.session;
    }
    
    protected void beginTransaction()
    {
        this.session = this.sessionFactory.openSession();
        this.session.beginTransaction();
    }
    
    protected void closeTransaction()
    {
        this.session.getTransaction().commit();
        this.session.close();
    }
    
    /**
     * <save obj to db>
     * <Detailed description of function>
     * @param object
     * @return
     * @see [class/function]
     */
    public Object save(Object object)
    {
        
        try
        {
            beginTransaction();
            session.save(object);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
        
        return object;
    }
    
    /**
     * <delete obj from db>
     * <Detailed description of function>
     * @param object
     * @see [class/function]
     */
    public void delete(Object object)
    {
        try
        {
            beginTransaction();
            session.delete(object);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
    }
    
    /**
     * <update db info>
     * <Detailed description of function>
     * @param object
     * @see [class/function]
     */
    public void update(Object object)
    {
        try
        {
            beginTransaction();
            session.update(object);
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage(), e);
        }
        finally
        {
            closeTransaction();
        }
    }
}
